<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\MLog;
use Bican\Roles\Models\Permission;
use Bican\Roles\Models\Role;
use DB;
use Exception;
use Illuminate\Http\Request;

/**
 * 管理员控制器
 */
class AdminController extends Controller
{
    /**
     * 管理员列表
     */
    public function adminsPage()
    {
        $this->data['admins'] = Admin::where('super', 0)->get();
        return view("admin.admins")->with($this->data);
    }

    /**
     * 管理员信息编辑界面
     */
    public function adminsEditPage(Request $request, $id = 0)
    {
        $this->data['admin'] = Admin::find($id);
        return view('admin.admin_edit')->with($this->data);
    }

    /**
     * 管理员信息保存
     */
    public function adminsSave(Request $request, $id = 0)
    {
        if (!$this->validateReq($request, Admin::saveRulesWithMsg(0), Admin::saveRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }

        //新添加管理员需检查管理员是否重名
        $admin = Admin::find($id);
        if (empty($admin)) {
            $admin = new Admin();
            if ($admin->existUserName($request->username)) {
                $this->data = $this->makeJsCode(1, "用户名已经存在！");
                return response()->json($this->data);
            }
        }

        try {
            DB::transaction(function () use ($request, $admin) {
                if ($admin->createOrSave($request)) {
                    $this->data = $this->makeJsCode(0, "保存管理员成功！");
                    MLog::log("修改了管理员 $admin->username 的数据");
                } else {
                    $this->data = $this->makeJsCode(1, "保存管理员失败！");
                }
            });
        } catch (Exception $e) {
            $this->data = $this->makeJsCode(1, "保存管理员失败！");
        }
        return response()->json($this->data);
    }

    /**
     * 删除管理员
     */
    public function adminDel($id = 0)
    {
        $admin = Admin::find($id);
        if (!empty($admin)) {
            $admin->delete();
            $this->data = $this->makeJsCode(0, "删除成功！");
            MLog::log("删除了管理员 $admin->username !");
        } else {
            $this->data = $this->makeJsCode(1, "要删除的管理员不存在！");
        }
        return back()->with($this->data);
    }

}